// Files stored in my folder
var serviceURL = "https://mathlab.utsc.utoronto.ca/courses/cscc09f12/linhsieh/a2/"

// Files in prof's folder
var rosseletURL = "http://www.utsc.utoronto.ca/~rosselet/cscc09f12/asn/services/"

// Global variables? Bad design but don't know
var fromPage

/*
===================================================================
 * Utility Functions
===================================================================
 */

/* Takes the arrival time of the next bus, in seconds,
 * and returns the local time of the next bus.
 */
function get_time(nextSec) {
	var currentTime = new Date()
	currentTime.setSeconds(currentTime.getSeconds() + nextSec)
	return currentTime.toLocaleTimeString()
}

/* Put a 24-hr clock on our page
 */
function updateClock(){
	var currentTime = new Date ( );
	var currentHours = currentTime.getHours ( );
	var currentMinutes = currentTime.getMinutes ( );
	var currentSeconds = currentTime.getSeconds ( );

	currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
	currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
	var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds;

	$("#clock").html(currentTimeString);
}

/* Check whether an "authenticated" attribute
 * exists in the current session.
 */
function checkAuthentication()
{	
	
	var loggedIn = false
	$.ajax({
		url: "/a2/authenticate.jsp",
		type: "POST",
		dataType: 'json',
		async: false,
		success: function(data, status) {
			loggedIn = (data.authenticated == "true")
		}, 
		error: function(x,y,z) {
			console.log(y)
		}
	});
	return loggedIn
}

function initialize_popups()
{
	$('#needLoginPopup' ).popup({ dismissable: false })
	$('#logoutPopup' ).popup({ dismissable: false })
	$('#deleteStopPopup').popup({ dismissable: false })
}

function createHeaderButtons(header)
{
	var loggedIn = checkAuthentication()
	header.html("")
	var buttons = '<div class="ui-btn-right">'
		+ '<a class="btn me" href="#my_page" data-role="button" data-icon="search" data-theme="b" data-inline="true" data-transition="slide">Me</a>' 
		+ '<a class="btn login" href="#" data-role="button" data-icon="gear" data-theme="b" data-inline="true" data-transition="slide">Login</a>'
		+ '</div>'
	header.append(buttons)
	$('.btn').button();
	
	if (loggedIn)
	{
		$('.login .ui-btn-text').html("Logout");
	}
	else
	{
		$('.login .ui-btn-text').html("Login");
	}
	
	// setup some popups
	initialize_popups()
}

/* Clear any forms when you go to the page again
 */
function clear_form(form)
{
	form.reset()	
	
	// remove any checkmarks
	$('label').removeClass('checked') 
}

/* Helper function that returns a dictionary holding saved stops
 * from local storage
 */
function getSavedStops()
{
	var myStopList
	var inData = {"action" : "get_stops"}
	
	$.ajax({
		url: "/a2/get_saved_stops.jsp",
		type: "POST",
		dataType: 'json',
		async: false,
		data: inData,
		success: function(data, status) {
			myStopList = data
		}, 
		error: function(x,y,z) {
			console.log(y)
		}
	});
	
	return myStopList;
}

/* Delete the specified stop, given a stop ID
 */
function deleteStop(stopId)
{
	var inData = {"stopId" : stopId }
	$.ajax({
		url: "/a2/delete_stop.jsp",
		type: "POST",
		dataType: 'json',
		data: inData,
		success: function(data, status) {
			showSavedStops()
		}, 
		error: function(x,y,z) {
			console.log(y)
		}
	});
}

/* Returns the previous page */
function getPrevPage()
{
	if (fromPage == null)
		return "#routes";
	else
		return fromPage;
}

/* Set the previous page so that we can go back to it after
 * logging in
 */
function setPrevPage(page)
{
	// set candidate page
	if (page == null)
		temp = "#" + $('.ui-page-active').attr('id');
	else
		temp = page;
	
	// only set it as the previous page if it is not the login page
	if (temp != "#login")
		fromPage = temp	
}

/*
===================================================================
 * Ajax calls
===================================================================
 */

/* Displays a list of routes */
function getRouteList()
{
	$.getJSON(serviceURL + "php/routes.php", function(data) {
		// extract the list of route dictionaries
		var routeList = data.items;  
		
		// delete the previous stuff
		$('#RouteList').html("")
		
		// Create links for each route
		$.each(routeList, function(index, route) {
			var RouteItem = '<li><a href="#page_directions" id="' + route.id + '" title="'
			+ route.display_name + '" data-role="button"'
			+ ' data-inline="true" data-mini="true" data-icon="arrow-r"'
			+ ' data-theme="b" class="btn getDir" data-transition="slide">'
			+ route.display_name + '</a></li>';
			
			// Add the link to the list
			$('#RouteList').append(RouteItem);
			
		});
		// Refresh view to update new links
		$('#RouteList').listview('refresh');
	})
}

/* Displays a list of directions, given a run ID */
function getDirList(id)
{
	$.getJSON(serviceURL + "php/runs.php?id=" + id, function(data) {
		// extract the list of route dictionaries
		var dirList = data.items;  
		
		// delete the previous stuff
		$('#dirList').html("")
		
		$.each(dirList, function(index, dir) {
			var DirItem = '<li><a href="#page_stops" id="' + dir.id // this is the run ID
			+ '" route_id="' + dir.route_id + '" directionName="'
			+ dir.direction_name + '" data-role="button"'
			+ ' data-inline="true" data-mini="true" data-icon="arrow-r"'
			+ ' data-theme="b" class="btn getStop" data-transition="slide">'
			+ dir.display_name + '</a></li>';
			$('#dirList').append(DirItem);
		});

		$('#dirList').listview('refresh');
	})
}

/* Displays a list of stops along the specified run, for the given
 * route
 */
function getStopList(route_id, run_id)
{
	$.getJSON(serviceURL + "php/stops.php?routeid=" +route_id + "&runid=" + run_id, function(data) {
		// extract the list of route dictionaries
		var stopList = data.items;  
		
		// delete the previous stuff
		$('#stopList').html('')
		
		// iterate through each stop and create heading and buttons for each entry
		$.each(stopList, function(index, stop) {
			var StopItem = '<li data-theme="f">'
			+ '<div class="ui-btn" data-theme="f">'
			+ '<div><h1>' + stop.display_name + '</h1></div>'
			+ '<a href="#save_popup" data-rel="popup" class="btn saveStop" id="' + stop.id + '" '
			+ 'stopName="' + stop.display_name + '" runid= "' + run_id + '" '
			+ 'data-role="button" data-inline="true" data-mini="true" data-icon="star" data-iconpos="right" data-theme="b"  data-transition="slide">Save Stop</a>'
			+ '<a href="#page_predictions" class="btn predictStop" id="' + stop.id + '" stopName="' + stop.display_name + '" data-role="button" data-inline="true" data-mini="true" data-icon="arrow-r" data-iconpos="right" data-theme="b"  data-transition="slide">Predict Arrivals</a>'
			+ '</li>'			
			$('#stopList').append(StopItem);
		});
		
		/* refresh the browser view to show the newly inserted DOM elements */
		$('#stopList').listview('refresh');
		
		// Make them look like buttons
		$('.btn').button();
	})
}

/* Displays a list of saved stops stored in local storage */
function showSavedStops()
{
	var myStopList = getSavedStops();
	// delete the previous stuff
	$('#myStopList').html("")
	$.each(myStopList, function(index, stop) {
		var StopItem = '<li data-theme="f">'
			+ '<div class="ui-btn">'
			+ '<div><h1>' + stop.routeid + " at " + stop.name + '</h1></div>'
			+ '<a href="#page_predictions" class="btn predictStop" id="' + stop.id
			+ '" data-role="button" data-inline="true" data-mini="true"'
			+ ' data-icon="arrow-r" data-theme="b"  data-transition="slide">Prediction</a>'
			+ '<a href="#" class="btn delete" id="' + stop.id
			+ '" stopName="' + stop.name + '" data-rel="popup" data-role="button" data-inline="true" data-mini="true" '
			+ 'data-icon="delete" data-theme="b"  data-position-to="window" data-transition="pop">Delete</a>'
			+ '</div></li>'			
			$('#myStopList').append(StopItem);
	})
	$('.btn.predictStop').button();
	$('.btn.delete').button();
	$('#myStopList').listview('refresh');
	
}

/* Displays a list of predictions for a stop, given the stopID */
function getPredictionList(stopID)
{
	$.getJSON(rosseletURL + "getpredictions.php?id=" + stopID, function(data) {
		// extract the list of route dictionaries
		var predictList = data.items;  
		
		// delete the previous stuff
		$('#predictList').html("")
		/* iterate through the CD dictionary list, building an HTML list
		with attributes drawn from the dictionary fields.
		*/
		$.each(predictList, function(index, prediction) {
			var PredictItem = '<li data-theme="f><p class="predictListItem" >Route ' + prediction.route_id + ' at ' + get_time(prediction.seconds) + '</p></li>'
			
			/* '<li><p data-role="button"'
			+ ' data-inline="true" class="predictList"'
			+ ' data-theme="b" data-transition="slide" data-inset="true">'
			+ ' Route ' + prediction.route_id + ' at ' + get_time(prediction.seconds) + '</a></li>';*/
			/* append the new list item into the element with * id=CDList */
			$('#predictList').append(PredictItem);
		});
		/* refresh the browser view to show the newly inserted DOM elements */
		$('.predictList').button();
		$('#predictList').listview('refresh');
	})
}

/*
===================================================================
 * Event Triggers
===================================================================
 */

/* Initialize the app */
$(document).ready(function() {
	initialize_popups();
	setInterval('updateClock()', 1000);
})

/* Show list of routes when page is initialized. Just a hack, not sure
 * why the popups are not being initialized at this point when you
 * directly access the page
 */
$('#routes').live("pageshow", function(event) {
	createHeaderButtons($('#routes .header'));
	getRouteList();
});

/* Show list of directions when the directions page is displayed */
$('#page_directions').live("pagebeforeshow", function(event) {
	createHeaderButtons($('#page_directions .header'));
});

$('#page_directions').live("pageshow", function(event) {
	var route_id = $(this).attr('route_id')
	getDirList(route_id);
});

/* Shows list of stops when the stops page is displayed */
$('#page_stops').live("pagebeforeshow", function(event) {
	createHeaderButtons($('#page_stops .header'));
	var route_id = $(this).attr('route_id')
	var run_id = $(this).attr('run_id')
	var dirName = $(this).attr('dirName')
	getStopList(route_id,run_id);
});

/* Get list of predictions for the specified stop and update the
 * page before the page is displayed
 */
$('#page_predictions').live('pagebeforeshow', function(event) {
	createHeaderButtons($('#page_predictions .header'));
	var stopID = $(this).attr('stopID')
	getPredictionList(stopID);
})

/* Shows saved stops when `my stops` page is displayed */
$('#stops').live('pagebeforeshow', function(event) {
	createHeaderButtons($('#stops .header'));
	showSavedStops();
})

/* Maps page */
$('#maps').live('pagebeforeshow', function(event) {
	createHeaderButtons($('#maps .header'));
})

/* Info page*/
$('#info').live('pagebeforeshow', function(event) {
	createHeaderButtons($('#info .header'));
})

/* Login page */
$('#login').live('pagebeforeshow', function(event) {
	createHeaderButtons($('#login .header'));
	clear_form($('#loginForm')[0])
})

/* My Page */
$('#my_page').live('pagebeforeshow', function(event) {
	createHeaderButtons($('#my_page .header'));
})

/* Registration page*/
$('#page_register').live('pagebeforeshow', function(event) {
	$("#regSuccessPopup").popup();
	clear_form($('#registerForm')[0])
})

/* Set attributes for the directions page whenever any of the direction
 * links are clicked. Updates the page accordingly to reflect the
 * user's selection
 */
$('a.getDir').live("click", function(event) {
    var route_id = $(this).attr('id');  // get the id from the event link
    var route_name = $(this).attr('title');
	$('#dirPageHeader').html(route_name);
	$('#page_directions').attr({route_id: route_id, route_name: route_name});
});

/* Set attributes for the stops page whenever any of the stop
 * links are clicked. Updates the stop page accordingly to reflect the
 * user's selection
 */
$('a.getStop').live('click', function(event) {
	var route_id = $(this).attr('route_id');
	var run_id = $(this).attr('id');
	var dirName = $(this).attr('directionName')
	$('#stopPageHeader').html("Route " + route_id + " " + dirName);
	$('#page_stops').attr({route_id: route_id, run_id: run_id, dirName: dirName});
})	

/* Set attributes for the prediction page whenever any of the prediction
 * links are clicked. Updates the predict page accordingly to reflect the
 * user's selection
 */
$('a.predictStop').live('click', function(event) {
	var stopID = $(this).attr('id')
	var stopName = $(this).attr('stopName')
	$('#predictPageHeader').html(stopName);
	$('#page_predictions').attr({stopID: stopID, stopName: stopName});
})

$("#refresh_predictions").live('click', function(event) {
	var stopID = $('#page_predictions').attr('stopid')
	getPredictionList(stopID);
})

/* When the save button for a stop is clicked, the corresponding stop
 * is saved in local storage
 */
$('a.saveStop').live('click', function(event) {
	event.preventDefault()
	if (!checkAuthentication())
	{
		needLoginAlert()
	}
	else {
		var stopID = $(this).attr('id');  // gets the stopid from the save button
		var stopName = $(this).attr('stopName');
		var runid = $(this).attr('runid');
		
		stopData = {'stopId':stopID, 'runId' :runid}
		$.ajax({
			url: "/a2/save_stop.jsp",
			type: "POST",
			dataType: 'json',
			data: stopData,
			success: function(data, status) {
				showSavedAlert()
				setTimeout(function(){$("#saveStopPopup" ).popup("close");},1000);
			},
			error: function(x, y, z) {
				console.log(y);
			}
		});
	}
})

/* Prompt user to confirm delete request */
$('a.delete').live("click", function(event) {
	event.preventDefault()
	var stopID = $(this).attr('id')
	var stopName = $(this).attr('stopName');
	
	$('#deletePopupConfirm').attr({stopID : stopID, stopName : stopName})
	showDeleteAlert()
})

/* Delete the stop when we confirm our choice */
$('a.deleteStop').live("click", function(event) {
	var stopID = $(this).attr('stopID')
	deleteStop(stopID);
})

/* When we click on the login (or logout) button, check whether
 * the user is currently logged in or not and perform appropriate
 * action
 */
$('a.login').live("click", function(event) {
	event.preventDefault()
	setPrevPage();
	// If logged in, logout
	if (checkAuthentication())
	{
		$('.login .ui-btn-text').html("Login");
		$.ajax({
			url: '/a2/servlet/Controller',
			type: 'POST',
			dataType: 'json',
			data: {"action": "logout", "page": fromPage},
			success: function(data, status) {
				showLogoutAlert()
				
			},
			error: function(x, y, z)
			{
				console.log("Something went wrong");
			}
		});
	}
	else
	{
		$.mobile.changePage('#login')
	}
});

// Perform check to determine whether to go to login page or not
$('a.stops').live('click', function(event) {
	event.preventDefault()
	if (!checkAuthentication()) {
		setPrevPage("#stops")
		needLoginAlert()
	}
	else
		$.mobile.changePage("#stops")
});

/*
===================================================================
 * Popups and dialogs
===================================================================
 */

/* Inform user that authentication is required to use feature */
function needLoginAlert()
{
	$("#needLoginPopup").popup("open");
	setTimeout(function(){ $.mobile.changePage("#login")},1000);
}

/* Dialog that informs the user that a stop has been saved
 */
function showSavedAlert()
{
	$("#saveStopPopup" ).popup("open");
}

/* Inform user that registration was successful. Redirect to login page
 * after one second
 */
function showRegisterAlert()
{
	$("#regSuccessPopup").popup("open");
	setTimeout(function(){ $.mobile.changePage("#login")},1000);
}

/* Inform user that registration failed */
function showRegisterFailAlert()
{
	$("#regFailPopup").popup("open");
	setTimeout(function(){ $("#regFailPopup").popup("close");},1000);
}

/* Inform user that they are now logged in */
function showLoginAlert()
{
	$("#loginSuccessPopup").popup("open");
}

/* Inform user that login attempt failed */
function showLoginFailAlert()
{
	$("#loginFailPopup").popup("open")
	setTimeout(function(){ $("#loginFailPopup").popup("close");},1000);
}

/* Prompt user to confirm stop deletion */
function showDeleteAlert()
{
	$('#deleteStopDialog').popup("open");
}

function showLogoutAlert()
{
	$('#logoutPopup').popup("open");
	setTimeout(function(){ $.mobile.changePage("#login")},1000);
}

/*
===================================================================
 * Form submitting
===================================================================
 */

$('#loginForm').live('submit', function(event) {
	event.preventDefault()
	var loginData = $(this).serializeArray()
	loginData.push({ name: "page", value: getPrevPage() });
	var form = $('#loginForm');
	$.ajax({
		url: form.attr('action'),
		type: form.attr('method'),
		dataType: 'json',
		data: loginData,
		success: function(data, status) {
			loggedIn = data.authenticated;
			if (loggedIn == 'true') {
				// Logout currently not implemented, also Logout does not change state
				// when autologout occurs on server - need to test loggedIn state after
				// each server request.
				showLoginAlert()
				setTimeout(function(){$.mobile.changePage(data.page)},2000);
				return false;
			}
			else {
				showLoginFailAlert()
			};
			
			return true;  // prevent default page-oriented submit action
			}, 
		error: function(x,y,z) {
			console.log(y)
		}
	});
})

$('#registerForm').live("submit", function(ev) {
	ev.preventDefault();
	var regData = $(this).serializeArray()
	var form = $('#registerForm');
	$.ajax({
		url: form.attr('action'),
		type: form.attr('method'),
		dataType: 'json',
		data: regData,
		success: function(data, status) {
			if (data.registered == "true")
			{
				showRegisterAlert()
				return true
			}
			else
			{
				showRegisterFailAlert()
				return true
			}
		},
		error: function(x, y, z) {
			alert('fail')
			console.log(y);
		}
	});
})
